package pin

import (
	"fmt"
	"os"
)

// Determine if a specific pin is exported.
func isPinExported(number int) (bool, error) {
	_, err := os.Stat(fmt.Sprintf("/sys/class/gpio/gpio%d", number))
	if err != nil {
		if !os.IsNotExist(err) {
			return false, err
		}
		return false, nil
	}
	return true, nil
}

// Export or unexport a specific pin.
func setPinExport(number int, export bool) error {
	var filename string
	if export {
		filename = "/sys/class/gpio/export"
	} else {
		filename = "/sys/class/gpio/unexport"
	}
	f, err := os.OpenFile(filename, os.O_WRONLY, 0)
	if err != nil {
		return err
	}
	defer func() {
		_ = f.Close()
	}()
	_, err = f.Write([]byte(fmt.Sprintf("%d\n", number)))
	if err != nil {
		return err
	}
	return nil
}

// Set the direction of a pin.
func setPinDirection(number int, direction Direction) error {
	filename := fmt.Sprintf("/sys/class/gpio/gpio%d/direction", number)
	f, err := os.OpenFile(filename, os.O_WRONLY, 0)
	if err != nil {
		return err
	}
	defer func() {
		_ = f.Close()
	}()
	var data []byte
	switch direction {
	case IN:
		data = []byte("in\n")
	case OUT:
		data = []byte("out\n")
	}
	_, err = f.Write(data)
	return err
}
